<template>
  <el-row>
   <!-- <el-col :span="4">
      <div class="box">
        <el-scrollbar>
          <basic-container>
            <avue-tree :option="treeOption" :data="treeData" @node-click="nodeClick"/>
          </basic-container>
        </el-scrollbar>
      </div>
    </el-col> -->
    <el-col :span="24">
      <basic-container>
        <avue-crud :option="option"
                   :search.sync="search"
                   :table-loading="loading"
                   :data="data"
                   ref="crud"
                   v-model="form"
                   :permission="permissionList"
                   @row-del="rowDel"
                   @row-update="rowUpdate"
                   @row-save="rowSave"
                   :before-open="beforeOpen"
                   :page.sync="page"
                   @search-change="searchChange"
                   @search-reset="searchReset"
                   @selection-change="selectionChange"
                   @current-change="currentChange"
                   @size-change="sizeChange"
                   @refresh-change="refreshChange"
                   @on-load="onLoad">
          <template slot-scope="{row}"
                    slot="roleName">
            <el-tag>{{row.roleName}}</el-tag>
          </template>
          <template slot-scope="{row}"
                    slot="deptName">
            <el-tag>{{row.deptName}}</el-tag>
          </template>
          <template slot-scope="scope" slot="menu">
            <el-button
              type="text"
              size="small"
              icon="el-icon-edit"
              @click.stop="handleReset(scope.row.id)"
            >重置密码
            </el-button>
          </template>
        </avue-crud>
      </basic-container>
    </el-col>
  </el-row>
</template>

<script>
  import {
    getList,
    getUser,
    getUserPlatform,
    remove,
    update,
    updatePlatform,
    add,
    resetPassword
  } from "@/api/system/user";
  import {exportBlob} from "@/api/common";
  import {getDeptTree, getLazyList} from "@/api/system/dept";
  import {getRoleList} from "@/api/system/role";
  import {mapGetters} from "vuex";
  import website from '@/config/website';
  import {getToken} from '@/util/auth';
  import {downloadXls} from "@/util/util";
  import {dateNow} from "@/util/date";
  import NProgress from 'nprogress';
  import 'nprogress/nprogress.css';
  import func from "@/util/func";
import { List } from "echarts";

  export default {
    data() {
      const validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          callback();
        }
      };
      const validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.form.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        form: {},
        search:{},
        roleBox: false,
        excelBox: false,
        platformBox: false,
        initFlag: true,
        selectionList: [],
        query: {},
        loading: true,
        platformLoading: false,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        platformPage: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        init: {
          roleTree: [],
          deptTree: [],
        },
        props: {
          label: "title",
          value: "key"
        },
        roleGrantList: [],
        roleTreeObj: [],
        treeDeptId: 1,
        treeData: [],
        treeOption: {
          nodeKey: 'id',
          lazy: false,
          treeLoad: function (node, resolve) {
            // console.log(node)
            // const parentId = (node.level === 0) ? 0 : node.data.id;
            // getLazyList(parentId).then(res => {
            //   resolve(res.data.data.map(item => {
            //     return {
            //       ...item,
            //       leaf: !item.children
            //     }
            //   }))
            // });
          },
          addBtn: false,
          menu: false,
          size: 'small',
          props: {
            labelText: '标题',
            label: 'deptName',
            value: 'id',
            children: 'children'
          }
        },
        option: {
          columnBtn: false,
          searchShowBtn:false,
          height: 'auto',
          calcHeight: 80,
          tip: false,
          searchShow: false,
          searchMenuSpan: 6,
          border: true,
          index: true,
          selection: false,
          emptyText:'暂无数据',
          viewBtn: true,
          dialogType: 'drawer',
          dialogClickModal: false,
          menuWidth: 280,
          column: [
            {
              label: "登录账号",
              prop: "account",
              width:100,
              search: true,
              display: false
            },
            {
              label: "用户姓名",
              prop: "userName",
              search: true,
              display: false
            },
            {
              label: "机构部门",
              prop: "deptName",
              slot: true,
              display: false
            },
            {
              label: "角色",
              prop: "roleName",
              slot: true,
              display: false
            },
            {
              label: "状态",
              prop: "status",
              width:60,
              type: "radio",
              display: false,
                dicData: [
                  {
                    label: "启用",
                    value: 1
                  },
                  {
                    label: "禁用",
                    value: 0
                  }
                ],
              },
          ],
          group: [
            {
              label: '基础信息',
              prop: 'baseInfo',
              icon: 'el-icon-user-solid',
              column: [
                {
                  label: "登录账号",
                  prop: "account",
                  rules: [{
                    required: true,
                    message: "请输入登录账号",
                    trigger: "blur"
                  }],
                },
                {
                  label: "用户姓名",
                  prop: "realName",
                  rules: [{
                    required: true,
                    message: "请输入用户姓名",
                    trigger: "blur"
                  }, {
                    min: 2,
                    max: 5,
                    message: '姓名长度在2到5个字符'
                  }]
                },
                {
                  label: "所属角色",
                  prop: "roleId",
                  multiple: false,
                  type: "select",
                  dicData: [],
                  props: {
                    label: "name",
                    value:'id'
                  },
                  checkStrictly: true,
                  slot: true,
                  rules: [{
                    required: true,
                    message: "请选择所属角色",
                    trigger: "click"
                  }]
                },
                {
                  label: "所属部门",
                  prop: "deptId",
                  type: "tree",
                  multiple: false,
                  dicData: [],
                  props: {
                    label: "deptName",
                    value:'id'
                  },
                  checkStrictly: true,
                  slot: true,
                  rules: [{
                    required: true,
                    message: "请选择所属部门",
                    trigger: "click"
                  }]
                },
                {
                  label: "账号状态",
                  prop: "status",
                  type: "radio",
                  value:1,
                  required: true,
                  dicData: [
                    {
                      label: "启用",
                      value: 1
                    },
                    {
                      label: "禁用",
                      value: 0
                    }
                  ],
                },
              ]
            },
          ]
        },
        data: [],
      };
    },
    watch: {
      'form.tenantId'() {
        if (this.form.tenantId !== '' && this.initFlag) {
          this.initData(this.form.tenantId);
        }
      },
      'excelForm.isCovered'() {
        if (this.excelForm.isCovered !== '') {
          const column = this.findObject(this.excelOption.column, "excelFile");
          column.action = `/api/blade-system/user/import-user?isCovered=${this.excelForm.isCovered}`;
        }
      }
    },
    computed: {
      ...mapGetters(["userInfo", "permission"]),
      permissionList() {
        return {
          // addBtn: this.vaildData(this.permission.user_add, false),
          // viewBtn: this.vaildData(this.permission.user_view, false),
          // delBtn: this.vaildData(this.permission.user_delete, false),
          // editBtn: this.vaildData(this.permission.user_edit, false)
        };
      },
      platformPermissionList() {
        return {
          addBtn: false,
          viewBtn: false,
          delBtn: false,
          editBtn: this.vaildData(this.permission.user_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      },
    },
    mounted() {
      // 非租户模式默认加载管理组数据
      if (!website.tenantMode) {
        this.initData(website.tenantId);
      }
    },
    methods: {
      nodeClick(data) {
        this.treeDeptId = data.id;
        this.page.currentPage = 1;
        this.onLoad(this.page);
      },
      fliterMydepart(data){
        let userinfo = localStorage.getItem('sryx-userInfo');
        let departid = JSON.parse(userinfo).content.depart_id;
        let newdata = [];
        for(var i= 0;i<data.length;i++){
          if(data[i]['id'] == departid ){
            newdata.push(data[i])
          }
        }
        return newdata
      },
      initData(tenantId) {
        getRoleList(tenantId).then(res => {
          const column = this.findObject(this.option.group, "roleId");
          let result = res.data.data;
          let newdata = [];
          for(var i= 0;i<result.length;i++){
            if(result[i]['id'] != 10 && result[i]['id'] != 2){
              newdata.push(result[i])
            }
          }
          column.dicData = newdata;
        });
        getDeptTree(tenantId).then(res => {
          const column = this.findObject(this.option.group, "deptId");
          column.dicData = this.fliterMydepart(res.data.data);
        });
        getLazyList().then(res => {
          this.treeData = res.data.data;
          this.treeDeptId = 1;
        });
      },
      rowSave(row, done, loading) {
        row.deptId = func.join(row.deptId);
        row.roleId = func.join(row.roleId);
        let userinfo = localStorage.getItem('sryx-userInfo');
        let departid = JSON.parse(userinfo).content.depart_id;
        row.companyId = func.join(departid);
        delete row.deptName;
        delete row.roleName;
        delete row.userName;
        add(row).then(() => {
          this.initFlag = false;
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        row.deptId = func.join(row.deptId);
        row.roleId = func.join(row.roleId);
        row.postId = func.join(row.postId);
        delete row.deptName;
        delete row.roleName;
        delete row.userName;
        delete row['depart_id']
        delete row['role_id']
        delete row['created_at']
        delete row['updated_at']
        update(row).then(() => {
          this.initFlag = false;
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      searchReset() {
        this.query = {};
        this.treeDeptId = '';
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      handleReset(id) {
        this.$confirm("确定将选择账号密码重置为123456?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return resetPassword(id);
          })
          .then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      uploadAfter(res, done, loading, column) {
        window.console.log(column);
        this.excelBox = false;
        this.refreshChange();
        done();
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getUser(this.form.id).then(res => {
            let formdata = res.data.data;
            this.form = formdata;
            if(this.form.hasOwnProperty("deptId")){
              this.form.deptId = this.form.deptId;
            }
            if(this.form.hasOwnProperty("roleId")){
              this.form.roleId = this.form.roleId;
            }
          });
        }
        this.initFlag = true;
        done();
      },
      currentChange(currentPage) {
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        let userinfo = localStorage.getItem('sryx-userInfo');
        let departid = JSON.parse(userinfo).content.depart_id;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query), departid).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.list;
          this.loading = false;
          this.selectionClear();
        });
      },
      platformRowUpdate(row, index, done, loading) {
        updatePlatform(row.id, row.userType, row.userExt).then(() => {
          this.platformOnLoad(this.platformPage);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      platformBeforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getUserPlatform(this.platformForm.id).then(res => {
            this.platformForm = res.data.data;
          });
        }
        done();
      },
      platformSearchReset() {
        this.platformQuery = {};
        this.platformOnLoad(this.platformPage);
      },
      platformSearchChange(params, done) {
        this.platformQuery = params;
        this.platformPage.currentPage = 1;
        this.platformOnLoad(this.platformPage, params);
        done();
      },
      platformSelectionChange(list) {
        this.platformSelectionList = list;
      },
      platformSelectionClear() {
        this.platformSelectionList = [];
        this.$refs.platformCrud.toggleSelection();
      },
      platformCurrentChange(currentPage) {
        this.platformPage.currentPage = currentPage;
      },
      platformSizeChange(pageSize) {
        this.platformPage.pageSize = pageSize;
      },
      platformRefreshChange() {
        this.platformOnLoad(this.platformPage, this.platformQuery);
      },
      platformOnLoad(page, params = {}) {
        this.platformLoading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query), this.treeDeptId).then(res => {
          const data = res.data.data;
          this.platformPage.total = data.total;
          this.platformData = data.list;
          this.platformLoading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
  .box {
    height: 800px;
  }

  .el-scrollbar {
    height: 100%;
  }

  .box .el-scrollbar__wrap {
    overflow: scroll;
  }
</style>
